import axios from 'axios';
import { mockDevices, mockParcels, mockPaths } from '../utils/mockData.js';

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 模拟数据
const mockData = {
  devices: mockDevices,
  paths: mockPaths,
  parcels: mockParcels
};

// 模拟延迟函数
const mockDelay = (data, delay = 500) => {
  return new Promise(resolve => {
    setTimeout(() => resolve({ success: true, data }), delay);
  });
};

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  async error => {
    console.warn('API请求失败，使用模拟数据:', error.message);
    
    // 根据URL返回对应的模拟数据
    const url = error.config?.url || '';
    
    if (url.includes('/devices')) {
      if (url.includes('/status/')) {
        const status = url.split('/status/')[1];
        const filteredDevices = mockData.devices.filter(d => d.status === status);
        return mockDelay(filteredDevices);
      }
      return mockDelay(mockData.devices);
    }
    
    if (url.includes('/paths')) {
      if (url.includes('/device/') && url.includes('/time-range')) {
        const deviceId = parseInt(url.split('/device/')[1].split('/')[0]);
        const devicePaths = mockData.paths.filter(p => p.deviceId === deviceId);
        return mockDelay(devicePaths);
      }
      if (url.includes('/device/')) {
        const deviceId = parseInt(url.split('/device/')[1]);
        const devicePaths = mockData.paths.filter(p => p.deviceId === deviceId);
        return mockDelay(devicePaths);
      }
      return mockDelay(mockData.paths);
    }
    
    if (url.includes('/parcels')) {
      if (url.includes('/area')) {
        const parcelId = parseInt(url.split('/parcels/')[1].split('/')[0]);
        const parcel = mockData.parcels.find(p => p.id === parcelId);
        const areaData = {
          parcelId,
          area: parcel?.area || 0,
          unit: "平方米",
          calculatedTime: new Date().toISOString()
        };
        return mockDelay(areaData);
      }
      return mockDelay(mockData.parcels);
    }
    
    return Promise.reject(error);
  }
);

// 设备相关API
export const deviceAPI = {
  // 获取所有设备
  getAllDevices: () => api.get('/devices'),
  
  // 根据ID获取设备
  getDeviceById: (id) => api.get(`/devices/${id}`),
  
  // 根据状态获取设备
  getDevicesByStatus: (status) => api.get(`/devices/status/${status}`),
  
  // 创建设备
  createDevice: (device) => api.post('/devices', device),
  
  // 更新设备位置
  updateDevicePosition: (id, longitude, latitude) => 
    api.put(`/devices/${id}/position`, null, {
      params: { longitude, latitude }
    }),
  
  // 删除设备
  deleteDevice: (id) => api.delete(`/devices/${id}`)
};

// 路径相关API
export const pathAPI = {
  // 获取所有路径
  getAllPaths: () => api.get('/paths'),
  
  // 根据ID获取路径
  getPathById: (id) => api.get(`/paths/${id}`),
  
  // 根据设备ID获取路径
  getPathsByDeviceId: (deviceId) => api.get(`/paths/device/${deviceId}`),
  
  // 根据设备ID和时间范围获取路径
  getPathsByDeviceAndTimeRange: (deviceId, startTime, endTime) => 
    api.get(`/paths/device/${deviceId}/time-range`, {
      params: { startTime, endTime }
    }),
  
  // 创建路径
  createPath: (pathData) => api.post('/paths', pathData)
};

// 地块相关API
export const parcelAPI = {
  // 获取所有地块
  getAllParcels: () => api.get('/parcels'),
  
  // 根据ID获取地块
  getParcelById: (id) => api.get(`/parcels/${id}`),
  
  // 获取地块面积
  getParcelArea: (id) => api.get(`/parcels/${id}/area`),
  
  // 创建地块
  createParcel: (parcel) => api.post('/parcels', parcel),
  
  // 删除地块
  deleteParcel: (id) => api.delete(`/parcels/${id}`)
};

// 导出模拟数据用于测试
export { mockData };
export default api;